//
//  GridNFCViewController.swift
//  grid-ios-app
//
//  Created by wondertek on 2024/3/26.
//

import UIKit
import CoreNFC
import Toast_Swift

class GridNFCViewController: GridBaseViewController {
    
    var gridNFCSession: NFCNDEFReaderSession?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = Theme.Color.Background.default
        navigationItem.title = "NFC"
        self.navigationController?.navigationBar.topItem?.title = "Home"
            let lbNavTitle = UILabel (frame: CGRect(x: 0, y: 0, width: 320, height: 40))
            lbNavTitle.backgroundColor = UIColor.red
            lbNavTitle.textColor = UIColor.black
            lbNavTitle.numberOfLines = 0
            lbNavTitle.center = CGPoint(x: 0, y: 0)
            lbNavTitle.textAlignment = .left
            lbNavTitle.text = "NFC"


            self.navigationItem.titleView = lbNavTitle
        
        // 设置支持NFC
        if NFCNDEFReaderSession.readingAvailable {
            gridNFCSession = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
            gridNFCSession?.begin()
            gridNFCSession?.alertMessage = "You can scan NFC-tags by holding them behind the top of your iPhone.";
        }
        else {
            UIWindow.grid_Window()?.makeToast("设备不支持NFC", duration: 3.0, position: .center)
        }
        
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}

extension GridNFCViewController: NFCNDEFReaderSessionDelegate {
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print("Error reading NFC: \(error.localizedDescription)")
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        for message in messages {
            for record in message.records {
                print("Type name format: \(record.typeNameFormat)")
                print("Payload: \(record.payload)")
                print("Type: \(record.type)")
                print("Identifier: \(record.identifier)")
            }
        }
    }
    
    
}
